package com.china.produce.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2025/8/9
 */
@Slf4j
@RocketMQTransactionListener
public class OrderTxListener implements RocketMQLocalTransactionListener {

    // 执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        String orderId = (String) arg;
        log.info("执行本地事务: {}", orderId);

        try {
            // 模拟本地事务逻辑
            if ("fail".equals(orderId)) {
                log.error("订单创建失败，回滚事务消息");
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            // 本地事务成功
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            log.error("本地事务异常", e);
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }

    // 回查本地事务状态（Broker 调用）
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        String orderId = (String) msg.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        log.info("回查本地事务状态: {}", orderId);

        // 模拟从数据库查询事务执行结果
        boolean status = queryOrderStatus(orderId);
        return status ? RocketMQLocalTransactionState.COMMIT : RocketMQLocalTransactionState.ROLLBACK;
    }

    private boolean queryOrderStatus(String orderId) {
        // 模拟查询数据库，这里默认查到成功
        return Boolean.TRUE;
    }

}
